package chapter1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
	public final static String WWW_ROOT = ClassLoader.getSystemResource("chapter1").getPath();

	// shutdown command
	private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

	// the shutdown command received
	private boolean shutdown = false;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HttpServer server=new HttpServer();
		server.await();
	}
	public void await(){
		ServerSocket serverSocket=null;
		int port =18080;
		try {
			serverSocket=new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(-1);
		}
		while(!shutdown){
			Socket client=null;
			InputStream is=null;
			OutputStream os=null;
			try {
				client=serverSocket.accept();
				os=client.getOutputStream();
				is=client.getInputStream();
				Request request=new Request(is);
				request.parse();
				if(request.getUri()!=null){
					Response response=new Response(os);
					response.setRequest(request);
					response.sendResource();
					shutdown = request.getUri().equals(SHUTDOWN_COMMAND); 
				}
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
			finally{
				try {
					if(os!=null )os.close();
					if(is!=null )is.close();
					if(client!=null )client.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
